/*
 * DA6.c
 *
 * Created: 4/21/2015 7:34:37 PM
 *  Author: David Hunt
 */ 

#include <avr/io.h>

#define PCF8591_ADDR 0x48		//address of the PCF8591

void i2c_stop(void)
{
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);	//INITIALIZE TWI
}

void i2c_write(unsigned int data)
{
	TWDR = data;						//STORE DATA IN REGISTER
	TWCR = (1<<TWINT) | (1<<TWEN);		//START TRANSMITTING
	while ((TWCR & (1<<TWINT)) == 0);	//WAIT UNTIL FINISHED
}

void i2c_start(void)
{
	TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);	//START TRANSMITTING START SIGNAL
	while ((TWCR & (1<<TWINT)) == 0);	//WAIT UNTIL FINISHED
}

void i2c_init(void)
{
	TWSR = 0x00;			//SET PRESCALER BITS TO ZERO
	TWBR = 0x47;			//SCL FREQUENCY IS 50K FOR 8M CLK
	TWCR = 0x04;			//ENABLE TWI MODULE
}

int main(void)
{
	ADCSRA = 0x87;		//ENABLE ADC AND PRESCALE CK/128
	ADMUX = 0xC0;		//2.56V VREF, ADC0 SINGLE ENDED INPUT, DATA RIGHT JUSTIFIED0
	DDRC = 0b00110000;	//SET PORTC AS INPUT FOR ADC EXCEPT FOR PINS4 AND 5.
	i2c_init();			//INITIALIZE MASTER
	
    while(1)
    {
		//ADC CONVERSION
		ADCSRA |= (1<<ADSC);			//STARTING CONVERSION
		while((ADCSRA&(1<<ADIF))==0);	//WAIT FOR CONVERSION TO FINISH
		unsigned int DATA=ADCL;			//SET VARIABLE BASED ON RESULT OF CONVERSION

		//TRANSMIT SIGNAL
		i2c_start();				//TRANSMIT START CONDITION
		i2c_write(PCF8591_ADDR);	//TRANSMIT ADDRESS OF SLAVE
		i2c_write(DATA);			//TRANSMIT DATA
		i2c_stop();					//TRANSMIT STOP CONDITION
	}
}